<template>
  <div class="app-container">
    <el-form :model="form" ref="formRef" :scroll-to-error="true" v-loading="formLoading">
      <el-space direction="vertical">
        <div shadow="never" class="assess">
          <el-row justify="center" class="task-title assess-title">
            <el-form-item label="当前任务编号：" prop="assessCode">
              <span>{{ form.assessCode }}</span>
            </el-form-item>
            <el-form-item label="当前任务名称：" prop="assessName">
              <span>{{ form.assessName }}</span>
            </el-form-item>
          </el-row>
          <el-row justify="center" class="assess-title">
            <el-form-item label="评估区域：" prop="list">
              {{ form.list?.map(item => {
                let area = []
                item.ppName && area.push(item.ppName)
                item.cityName && area.push(item.cityName)
                item.name && area.push(item.name)
                return area
              }).map(item => item.join('-')).join('、')
              }}
            </el-form-item>
            <el-form-item label="房屋基础数据：" prop="houseDataFlag">
              {{ houseBasicData.find(item => item.value == form.houseDataFlag)?.name }}
            </el-form-item>
            <el-form-item label="评估方式：" prop="assessType">
              <span> {{ assessType.find(item => item.value == form.assessType)?.name }} </span>
            </el-form-item>
            <el-form-item label="地震输入方式：" prop="seismicInputMode">
              <span>
                {{ inputMode?.map(item => seismicInputMode.find(cur => cur.value == item).name).join('、') }}
              </span>
            </el-form-item>
          </el-row>
        </div>
      </el-space>
      <template v-if="isCurTask">
        <el-space direction="vertical" v-if="form.assessType == '0'">
          <div shadow="never" class="assess">
            <el-row>
              <el-form-item label="危险性数据" prop="seismicInputMode1" style="display:block;width: 100%;">
                <el-row>
                  <el-radio-group v-model="form.seismicInputMode">
                    <el-radio v-for="item in inputMethods(form.assessType == '0' ? 'confirm' : 'probability')"
                      :key="item.value" :label="item.value" size="large" v-show="inputMode?.includes(item.value)">
                      {{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </el-row>
              </el-form-item>
            </el-row>
          </div>
        </el-space>
        <el-row style="margin: 10px 0;">
          <el-button plain @click="calculationFunc">计算区划值</el-button>
        </el-row>
        <el-space direction="vertical">
          <div shadow="never" class="assess">
            <el-row>
              <el-form-item label="危险性数据" prop="seismicInputMode1" style="display:block;width: 100%;">
                <el-row justify="space-between">
                  <el-radio-group v-model="form.seismicInputMode1" @change="seismicInputMode1Change">
                    <el-radio v-for="item in inputMethods(form.assessType == '0' ? 'confirm' : 'probability')"
                      :key="item.value" :label="item.value" size="large" v-show="inputMode?.includes(item.value)">
                      {{ item.name }}
                      <el-select v-model="form.condition0" v-show="form.seismicInputMode1 == '0' && item.value == '0'">
                        <el-option v-for="item in dictData.intensity" :key="item.dictItemId" :label="item.dictItemName"
                          :value="item.dictItemCode" />
                      </el-select>
                      <el-select v-model="form.condition1" v-show="form.seismicInputMode1 == '1' && item.value == '1'">
                        <el-option v-for="item in dictData.probability" :key="item.dictItemId" :label="item.dictItemName"
                          :value="item.dictItemCode" />
                      </el-select>
                    </el-radio>
                  </el-radio-group>
                  <el-col>
                    <!-- <el-form-item label="T年" prop="years" v-if="form.assessType == '1'">
                      <el-select v-model="form.years">
                        <el-option v-for="item in form.year.split(',')" :key="item" :label="item" :value="item" />
                      </el-select>
                    </el-form-item> -->
                    <!-- <el-form-item label="T年" prop="years" v-if="form.assessType == '1'">
                      <span style="color: var(--el-input-text-color, var(--el-text-color-regular))">{{ form.years }}年</span>
                    </el-form-item> -->
                  </el-col>
                </el-row>
              </el-form-item>
            </el-row>
          </div>
        </el-space>
        <el-row style="margin: 10px 0">
          <el-button type="primary" @click="showEvaluateResult">查看区划值</el-button>
          <el-button type="primary" @click="showEvaluateResultMap">查看区划图</el-button>
        </el-row>
        <el-row style="margin: 10px 0">
          风险区划等级Ⅰ级区县{{ statisticsData['Ⅰ'] }}个，Ⅱ级区县{{ statisticsData['Ⅱ'] }}个，Ⅲ级区县{{ statisticsData['Ⅲ'] }}个，Ⅳ级区县{{
            statisticsData['Ⅳ'] }}个，Ⅴ级区县{{ statisticsData['Ⅴ'] }}个
        </el-row>
        <div v-show="!evaluateResultMap">
          <el-table :data="dataList" v-loading="loading" class="normal-table" border>
            <el-table-column label="省" prop="province" align="center"></el-table-column>
            <el-table-column label="市" prop="city" align="center"></el-table-column>
            <el-table-column label="区/县" prop="county" align="center"></el-table-column>
            <el-table-column label="烈度" prop="type" align="center"
              v-if="form.assessType == '0' && form.seismicInputMode1 == '0'">
              <template #default="{ row }">
                <dict-tag :code="CODE.ld" :value="row.type" />
              </template>
            </el-table-column>
            <el-table-column label="超越概率" prop="type" align="center"
              v-if="form.assessType == '0' && form.seismicInputMode1 == '1'">
              <template #default="{ row }">
                <dict-tag :code="CODE.sgglsz" :value="row.type" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="T年" prop="type" align="center" v-if="form.assessType == '1'"></el-table-column> -->
            <el-table-column label="风险等级" prop="level" align="center"></el-table-column>
          </el-table>
          <pagination style="margin-top: 15px" v-show="queryParams.total > 0" :total="queryParams.total"
            v-model:page="queryParams.page" v-model:limit="queryParams.rows" @pagination="viewTable" />
        </div>
        <div v-if="evaluateResultMap">
          <Index :dataType="dataType" :form="form"></Index>
        </div>
      </template>
      <template v-else>
        <Empty :description="`无${route.meta.title}评估`" />
      </template>
    </el-form>
  </div>
</template>

<script setup name="overallRiskZonationMap">
import { getTasks } from '@/api/building/index'
import { getDict } from '@/api/system/dict'
import { CODE, inputMethods, houseBasicData, seismicInputMode, assessType } from '@/views/building/index'
import Index from '@/map/buildingRiskZoning/overallRiskZonation/index.vue'
import { check, count, getResults, statistics } from '@/api/buildingRiskZoning/overallRiskZonation'
import { ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance()
const route = useRoute()
const dataType = ref("")
const form = ref({})
const formLoading = ref(false)
// 字典项
const dictData = ref({
  intensity: [],
  probability: [],
  years: []
})
const dictInit = () => {
  if (form.value.assessType == '0') {
    getDictData('intensity', CODE.ld, 'condition0')
    getDictData('probability', CODE.sgglsz, 'condition1')
  } else if (form.value.assessType == '1') {
    form.value.years = form.value.year.split(',')[0]
  }
}
const getDictData = (field, code, formField) => {
  getDict(code).then(res => {
    dictData.value[field] = res.data
    if (formField) {
      form.value[formField] = res.data[0].dictItemCode
    }
  })
}
const isCurTask = ref(false)
let inputMode = ref()
// 当前任务信息
const getCurrentTask = () => {
  formLoading.value = true
  
  getTasks().then(res => {
    if (res.data && res.code == 200) {
      form.value = { ...form.value, ...res.data }
      inputMode.value = res.data.seismicInputMode.split(',')
      form.value.seismicInputMode = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      form.value.seismicInputMode1 = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      dictInit()
      if (form.value.assessObj.split(',').length == 3) {
        isCurTask.value = true
      }
      if(res.data.assessType == '0') {
        dataType.value = 'overallRiskZonation'
      }else{
        dataType.value = 'overallRiskZonationGl'
      }
    }
    formLoading.value = false
  }).catch(() => { formLoading.value = false })
}
// 计算区划值
const calculationFunc = async () => {
  let { seismicInputMode, assessType, id } = form.value
  seismicInputMode = Number(seismicInputMode) >= 3 ? '3' : seismicInputMode
  let isCheckResult = await check({ seismicInputMode, assessType, id })
  // 是否可以进行计算
  if (!isCheckResult) {
    proxy.$modal.msgError('请先进行建筑物评估！')
    return
  }
  // 是否已有数据
  let category = assessType == '0' ? seismicInputMode : '3'
  let type = ''
  if (assessType == '0') {
    type = seismicInputMode == '2' ? '' : form.value[`condition${seismicInputMode}`]
  } else {
    type = form.value.years
  }
  let listResult = await getResults({ id, category, type, ...queryParams.value })
  // 计算区划值
  if (listResult.data && listResult.data.total > 0) {
    proxy.$modal.confirm('该任务下已有数据，是否确认覆盖？').then(() => {
      countZoning({ seismicInputMode, assessType, id })
    }).catch(() => { })
  } else {
    countZoning({ seismicInputMode, assessType, id })
  }
}

// const calculationFunc = async () => {
//   let { seismicInputMode1, assessType, id,years } = form.value
//   // 是否已有数据
//   let category = assessType == '0' ? seismicInputMode1 : '3'
//   let type = ''
//   if (assessType == '0') {
//     type = seismicInputMode1 == '2' ? '' : form.value[`condition${seismicInputMode1}`]
//   } else {
//     type = years
//   }
//   let isCheckResult = await check({ seismicInputMode:seismicInputMode1, assessType, id })
//   // 是否可以进行计算
//   if (!isCheckResult) {
//     proxy.$modal.msgError('请先进行建筑物评估！')
//     return
//   }
//   let listResult = await getResults({ id, category, type, ...queryParams.value })
//   // 计算区划值
//   if (listResult.data && listResult.data.total > 0) {
//     proxy.$modal.confirm('该任务下已有数据，是否确认覆盖？').then(() => {
//       countZoning({ seismicInputMode:seismicInputMode1, assessType, id })
//     }).catch(() => { })
//   } else {
//     countZoning({ seismicInputMode:seismicInputMode1, assessType, id })
//   }
// }
const countZoning = (data) => {
  const loading = ElLoading.service({
    lock: true,
    text: '计算中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  count(data).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('计算成功！')
      viewTable()
    }
    loading.close()
  }).catch(() => {
    loading.close()
  })
}
const queryParams = ref({
  page: 1,
  rows: 10,
  total: 0
})
const loading = ref(false)
const dataList = ref([])
const evaluateResultMap = ref(false)
const statisticsData = ref({
  'Ⅰ': 0,
  'Ⅱ': 0,
  'Ⅲ': 0,
  'Ⅳ': 0,
  'Ⅴ': 0,
})
// 查看区划值
const showEvaluateResult = () => {
  evaluateResultMap.value = false
  viewTable()
}
const viewTable = () => {
  loading.value = true
  const { seismicInputMode1, assessType, id, years } = form.value
  let category = assessType == '0' ? seismicInputMode1 : '3'
  let type = ''
  if (assessType == '0') {
    type = seismicInputMode1 == '2' ? '' : form.value[`condition${seismicInputMode1}`]
  } else {
    type = years
  }
  getResults({ id, category, type, ...queryParams.value }).then(res => {
    if (res.data && res.code == 200) {
      dataList.value = res.data.rows
      queryParams.value.total = res.data.total
    }
    loading.value = false
  }).catch(() => { loading.value = false })
  statistics({ id, category, type, ...queryParams.value }).then(res => {
    if (res.data?.length > 0) {
      Object.keys(statisticsData.value).forEach(key => {
        statisticsData.value[key] = res.data.find(item => item.level == key)?.count || 0
      })
    }
  })
}
// 查看区划图
const showEvaluateResultMap = () => {
  evaluateResultMap.value = true
}
const seismicInputMode1Change = val => {
  dataList.value = []
}
onMounted(() => {
  getCurrentTask()
})
</script>

<style lang="scss" scoped>
.assess-dialog.el-dialog .el-dialog__body {
  padding: 20px 20px;
}

.el-form-item.el-form-item--default {
  margin: 10px 0;
}

.assess-title {
  .el-form-item.el-form-item--default {
    margin: 10px 20px;
  }
}
:deep(.el-space) {
  width: 100%;

  &>.el-space__item {
    width: 100%;
  }
}

.assess {
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  .task-title {
    font-weight: bold;
    color: #606266;

    :deep(.el-form-item) {

      label,
      .el-form-item__content {
        font-size: 18px;
      }
    }
  }

  .border-bottom {
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-row {
    padding: 0 20px;
  }

  .title {
    font-weight: bold;
  }

  :deep(.column.el-radio-group) {
    flex-direction: column;
    align-items: start;

    &>.el-radio {
      &>.el-radio__label {
        &>.el-space {
          &>.el-space__item:first-of-type {
            margin-right: 50px !important;
          }
        }
      }
    }
  }
}
</style>